/*
 * 文件名：LoanFinController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月14日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.enums.hr.PostGroupEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.domain.ContractBankDomain;
import top.infopub.mgr.cap.domain.DropLoanFinDomain;
import top.infopub.mgr.cap.domain.LoanFinDomain;
import top.infopub.mgr.cap.dto.LoanFinDto;
import top.infopub.mgr.cap.service.*;
import top.infopub.mgr.cap.vo.LoanFinVo;
import top.infopub.mgr.cap.vo.RepaymentScheduleInfoVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.ContractInfo;
import top.infopub.model.cap.LoanFin;
import top.infopub.model.cap.LoanFinAtt;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 融资放款
 * @author wuzhiyang
 * @version 2020年1月14日
 * @see LoanFinController
 * @since
 */
@Controller
@RequestMapping("/loanFin")
public class LoanFinController extends GenericFlowController {

    @Autowired
    private LoanFinService loanFinService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private ContractBankService contractBankService;

    @Autowired
    private ContractInfoService contractInfoService;

    @Autowired
    private LoanContractService loanContractService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private CapProcessManageService capProcessManageService;
    /**
     * 融资立项列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "cap/lay-loanFin-list";
    }

    /**
     * 融资放款列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<LoanFinDomain> queryDataByCondition(LoanFinVo loanFinVo, ParamPage paramPage) {
        Page<LoanFinDomain> page = new Page<LoanFinDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (loanFinVo.getEndDate() != null) {
            loanFinVo.setEndDate(DateUtils.addDays(loanFinVo.getEndDate(), 1));
        }
        //查询时，放款结束日期增加一天
//        if (loanFinVo.getEndLoanDate() != null) {
//            loanFinVo.setEndLoanDate(DateUtils.addDays(loanFinVo.getEndLoanDate(), 1));
//        }
        //增加addby
        loanFinVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = loanFinService.selectByDomainWhere(page, loanFinVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资放款列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<LoanFinDomain> queryMyCheckDataByCondition(LoanFinVo loanFinVo,
                                                            ParamPage paramPage) {
        Page<LoanFinDomain> page = new Page<LoanFinDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (loanFinVo.getEndDate() != null) {
            loanFinVo.setEndDate(DateUtils.addDays(loanFinVo.getEndDate(), 1));
        }
        //查询时，放款结束日期增加一天
//        if (loanFinVo.getEndLoanDate() != null) {
//            loanFinVo.setEndLoanDate(DateUtils.addDays(loanFinVo.getEndLoanDate(), 1));
//        }
        //增加addby
        loanFinVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = loanFinService.selectMyCheckByDomainWhere(page, loanFinVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资立项-新增
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有融资合同审批通过中的项目名称
        List<ContractInfo> queryByProCode = contractInfoService.queryAll();
        request.setAttribute("allProName", queryByProCode);
        //返回所有承贷企业的单位名称
        List<CoopInfo> coopCode = coopInfoService.selectByCoopCode(null);
        request.setAttribute("coopInfoName", coopCode);
        return "cap/lay-loanFin-add";
    }

    /**
     * 通过项目id查询融资机构信息记录(带出)
     */
    @RequestMapping("/getBankByContractId")
    @ResponseBody
    public Map<String, Object> getBankByContractId(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String contractCode = request.getParameter("contractCode");
            List<ContractBankDomain> contractBankDomains = contractBankService.getBankDomainByContractId(contractCode.split("\\_")[0]);
            map.put("contractBankList", contractBankDomains);
        }
        catch (Exception e) {
            log.error("根据项目ID获取融资机构信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 通过项目id查询融资合同名称记录(带出)
     */
    @RequestMapping("/getContractNameByProCode")
    @ResponseBody
    public Map<String, Object> getContractNameByProCode(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCode = request.getParameter("proCode");
            List<ContractInfo> list = contractInfoService.queryByProCode(proCode);
            map.put("contractNameList", list);
        }
        catch (Exception e) {
            log.error("根据项目ID获取融资合同名称异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 融资放款-新增
     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/save")
//    @ResponseBody
//    public RspVo save(LoanFinAssist loanFinAssist) {
//
//        //主表-融资放款
//        loanFinAssist.setHrDeptId(loanFinAssist.getHrDeptid());
//        loanFinAssist.setHrOrgId(loanFinAssist.getHrOrgid());
//        loanFinAssist.setStaffName(loanFinAssist.getStaffname());
//        loanFinAssist.setHrStaffApplyId(loanFinAssist.getHrStaffApplyid());
//        loanFinAssist.setProCode(loanFinAssist.getProname());
//        List<ContractInfo> queryByProCode = contractInfoService.queryByProCode(loanFinAssist.getProname());
//        //添加项目名称
//        loanFinAssist.setProName(queryByProCode.get(0).getProName());
//        //添加城市调研信息ID
//        loanFinAssist.setSgCityId(queryByProCode.get(0).getSgCityId());
//        //添加融资合同id
//        loanFinAssist.setContractId(loanFinAssist.getContractCode().split("\\_")[0]);
//        loanFinAssist.setContractName(loanFinAssist.getContractCode().split("\\_")[1]);
//        //根据贷款品种判断融资信息字段是否显示
//        if (!"3".equals(loanFinAssist.getLoadType())) {
//            loanFinAssist.setCreditAmount(new BigDecimal(0));
//            loanFinAssist.setBondAmount(new BigDecimal(0));
//            loanFinAssist.setTicketAmount(new BigDecimal(0));
//        }
//        if ("3".equals(loanFinAssist.getLoadType())) {
//            loanFinAssist.setCapAmount(new BigDecimal(0));
//        }
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = IdFactory.getUUIDUpper();
//        loanFinAssist.setId(id);
//        loanFinAssist.setAddBy(vo.getId());
//        loanFinAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("cap_loan_fin");
//        loanFinAssist.setCodes(codes);
//        //处理processId
//        loanFinAssist.setProcessId(IdFactory.getUUIDUpper());
//        loanFinAssist.setProcessStatus("1");//审批中
//        loanFinAssist.setTypes("1");//PPP项目
//        loanFinAssist.setUptBy(vo.getId());
//        loanFinAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //融资合同金融机构明细
//        List<LoanFinBank> loanFinBanks = Lists.newLinkedList();
//        String[] subFinOrg = loanFinAssist.getFinOrg();
//        if (subFinOrg != null && subFinOrg.length > 0) {
//            for (int i = 0; i < subFinOrg.length; i++ ) {
//                String finOrg = subFinOrg[i];
//                String leader = loanFinAssist.getLeader()[i];
//                String capAmount = loanFinAssist.getCapAmounts()[i];
//                if (StringUtils.isEmpty(finOrg) && StringUtils.isEmpty(finOrg)) {
//                    continue;
//                }
//                String bankid = IdFactory.getUUIDUpper();//自动生成主键
//                LoanFinBank loanFinBank = new LoanFinBank();
//                loanFinBank.setId(bankid);
//                loanFinBank.setLoanFinId(id);
//                loanFinBank.setContractId(loanFinAssist.getContractId());
//                loanFinBank.setProCode(loanFinAssist.getProCode());
//                loanFinBank.setFinOrg(finOrg);
//                loanFinBank.setLeader(leader);
//                loanFinBank.setCapAmount(new BigDecimal(capAmount));
//                loanFinBank.setAddBy(vo.getId());
//                loanFinBank.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                loanFinBanks.add(loanFinBank);
//            }
//        }
//
//        //融资放款明细
//        List<LoanFinDetail> loanFinDetails = Lists.newLinkedList();
//        String[] subBankNameStr = loanFinAssist.getSubBankName();
//        if (subBankNameStr != null && subBankNameStr.length > 0) {
//            for (int i = 0; i < subBankNameStr.length; i++ ) {
//                String subBankName = subBankNameStr[i];
//                String bankName = loanFinAssist.getBankName()[i];
//                String loanRatio = loanFinAssist.getLoanRatio()[i];
//                String loanAmount = loanFinAssist.getLoanAmount()[i];
//                String loanInterestRate = loanFinAssist.getLoanInterestRate()[i];
//                if (StringUtils.isEmpty(subBankName) && StringUtils.isEmpty(subBankName)) {
//                    continue;
//                }
//                String detailId = IdFactory.getUUIDUpper();//自动生成主键
//                LoanFinDetail loanFinDetail = new LoanFinDetail();
//                loanFinDetail.setId(detailId);
//                loanFinDetail.setLoanFinId(id);
//                loanFinDetail.setBankName(bankName);
//                loanFinDetail.setSubBankName(subBankName);
//                loanFinDetail.setLoanRatio(new BigDecimal(loanRatio));
//                loanFinDetail.setLoanAmount(new BigDecimal(loanAmount));
//                loanFinDetail.setLoanInterestRate(new BigDecimal(loanInterestRate));
//                loanFinDetail.setAddBy(vo.getId());
//                loanFinDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                loanFinDetails.add(loanFinDetail);
//            }
//        }
//
//        //上传附件
//        List<LoanFinAtt> loanFinAtts = Lists.newLinkedList();
//        String[] fileAtts = loanFinAssist.getFileAtts();
//        if (fileAtts != null) {
//            for (String file : fileAtts) {
//                LoanFinAtt loanFinAtt = createFileAtt(vo, id, file);
//                loanFinAtts.add(loanFinAtt);
//            }
//        }
//        loanFinService.saveLoanFin(loanFinAssist, loanFinDetails, loanFinBanks, loanFinAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
//            "融资管理 -新增融资放款：项目名=" + loanFinAssist.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }

    private LoanFinAtt createFileAtt(AuthorizationVO vo, String loanFinId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        LoanFinAtt fileAtt = new LoanFinAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        fileAtt.setLoanFinId(loanFinId);//融资放款id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "loanFinAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传融资放款附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询融资放款详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 融资放款Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id",id);
        LoanFinVo loanFinVo = loanFinService.selectById(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("finFlag", "0");//指定财务人员进入审批页面必须填写财务信息
        if (loanFinVo!=null){
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), loanFinVo.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), loanFinVo.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(loanFinVo.getProcessId()) && loanFinVo.getProcessId().length() > 10){
                request.setAttribute("processId", loanFinVo.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(loanFinVo.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), loanFinVo.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                //查询指定财务节点人员ID
                List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(loanFinVo.getProcessId(), "-1", PostGroupEnum.FINANCE.getCode());
                if (finUserIdList != null && finUserIdList.size() > 0) {
                    for (String finUserId : finUserIdList) {
                        if (StringUtils.isBlank(finUserId)) continue;
                        if (StringUtils.equals(vo.getId(), finUserId)) {
                            //当前待审批节点=当前登录人，需要编辑财务信息提交
                            request.setAttribute("finFlag", "1");//指定财务人员进入审批页面必须填写财务信息
                        }
                    }
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return new ModelAndView("cap/lay-FinancingLoan-detail");
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String processId, String status, String auditMsg, LoanFin loanFin) {
        //融资付息审批
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        List<String> finUserIdList = capProcessManageService.queryFinanceUserIdByProcessId(processId, "-1", PostGroupEnum.FINANCE.getCode());
        if (finUserIdList != null && finUserIdList.size() > 0) {
            for (String finUserId : finUserIdList) {
                if (StringUtils.isBlank(finUserId)) continue;
                if (StringUtils.equals(vo.getId(), finUserId)) {
                    //当前待审批节点=当前登录人，需要编辑财务信息提交
                    if (loanFin == null || loanFin.getActualAmount() == null
                            || loanFin.getActualDate() == null) {
                        return RspVo.getFailureResponse(401, "财务还款情况不能为空");
                    }
                    RspVo rspVo = loanFinService.modifyFinInfo(loanFin, vo, processId);
                    if (!rspVo.isSuccess()) return rspVo;
                    break;
                }
            }
        }
        capProcessManageService.auditProject(loanFin.getId(), processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /**
     * 融资放款-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        LoanFinVo loanFinVo = loanFinService.selectById(id);
        request.setAttribute("loanFinVo", loanFinVo);
        //返回所有承贷企业的单位名称
        List<CoopInfo> coopCode = coopInfoService.selectByCoopCode(null);
        request.setAttribute("coopInfoName", coopCode);
        //带出融资合同名称
        String proCode = request.getParameter("proCode");
        List<ContractInfo> list = contractInfoService.queryByProCode(proCode);
        request.setAttribute("contractNameList", list);
        return "cap/lay-loanFin-copy";
    }

    /**
     * 融资放款列表数据
     * @return
     */
    @RequestMapping("/queryLoanByCondition")
    @ResponseBody
    public RspVo<LoanFinDomain> queryLoanByCondition(LoanFinVo loanFinVo, ParamPage paramPage) {
        Page<LoanFinDomain> page = new Page<LoanFinDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = loanFinService.selectByDomainWhere(page, loanFinVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /*
    *  详情下拉数据
    * */
    @RequestMapping("queryProject")
    @ResponseBody
    public RspVo queryProject(){
        //查找已通过合同评审的项目
      List<DropLoanFinDomain> dropLoanFinDomain =  loanContractService.selectProject();
      return RspVo.getSuccessResponse(dropLoanFinDomain);
    }

    //选择项目之后金融机构的下拉
    @RequestMapping("/queryLoan")
    @ResponseBody
    public RspVo queryLoan(String id){
        //使用id查找对应的金融机构
        List<RepaymentScheduleInfoVo> sublists = loanContractService.selectDockById(id);
        return RspVo.getSuccessResponse(sublists);
    }

    @RequestMapping("/financialDetail")
    @ResponseBody
    public RspVo financialDetail(String id){
       return loanFinService.financialDetail(id);
    }

    @RequestMapping("/queryById")
    @ResponseBody
    public RspVo queryById(String id){
       return loanFinService.queryById(id);
    }

    /***
     * 保存/新增
     * ***/
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String bodyStr,Integer submitType){
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        String s = StringEscapeUtils.unescapeJava(bodyStr);
        LoanFinDto vo = JSON.parseObject(s, LoanFinDto.class);
        /**
         * 附件处理
         * */
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(vo.getFileAtt()!=null){
            String[] fileAtt = vo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(userDtl,vo.getLoanFinVo().getProCode(),file);
                attachmentList.add(attachment);
            }
        }
        return loanFinService.saveAll(userDtl,vo.getLoanFinVo(),vo.getSetupFinancial(),attachmentList,s,submitType);
    }
}
